package com.edu.cq02.controller;

import com.edu.cq02.pojo.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
//@SessionAttributes(value = "userinfo1")
public class FileController {
    /**
     * 文件上传 io方式
     */
        @RequestMapping("fileload")
    public String fileLoad(MultipartFile[] files,
                             HttpServletRequest request) throws Exception {
        //设置上传的文件所存放的路径

        String path = request.getServletContext().getRealPath("/files");
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址："+realPath);
        ObjectMapper mapper = new ObjectMapper();
        //判断有没有文件上传
        if (files != null && files.length > 0) {
            //循环获取上传的文件
            for (MultipartFile file : files) {
                //获取上传文件的名称
                //时间戳拼接 防止提交重复
               // String filename = System.currentTimeMillis() + file.getOriginalFilename();
                //uuid拼接
                //嗨嗨嗨
                String filename = UUID.randomUUID().toString() + file.getOriginalFilename();
                InputStream is = file.getInputStream(); //文件输入流
                OutputStream os = new FileOutputStream(new File(realPath,filename)); //文件输出流
                //读取写出
                int len=0;
                byte[] buffer = new byte[1024];
                while ((len=is.read(buffer))!=-1){
                    os.write(buffer,0,len);
                    os.flush();
                }
                os.close();
                is.close();
                request.setAttribute("path", filename);
            }
            request.setAttribute("msg", "(上传成功)");

            return "forward:fileload.jsp";
        }
        request.setAttribute("msg", "(上传失败)");
        return "forward:fileload.jsp";
    }

    /**
     * 文件上传 transferTo方式
     */
    @RequestMapping("fileload1")
    public String fileLoad1(MultipartFile[] files,
                           HttpServletRequest request, User user) throws Exception {

        //设置上传的文件所存放的路径
        String path = request.getServletContext().getRealPath("/files");
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址："+realPath);
        ObjectMapper mapper = new ObjectMapper();
        if (files != null && files.length > 0) {
            //循环获取上传的文件
            for (MultipartFile file : files) {
                //获取上传文件的名称
                String filename = System.currentTimeMillis() + file.getOriginalFilename();
                file.transferTo(new File(realPath +"/"+ filename));
                request.setAttribute("path", filename);
            }
            request.setAttribute("msg", "(上传成功)");
            return "forward:fileload.jsp";
        }
        request.setAttribute("msg", "(上传失败)");
        return "forward:fileload.jsp";
    }
    /**
     * 文件上传 使用ajax
     */
    @RequestMapping("fileloadbyajax")
    @ResponseBody
    public ResultData fileLoadByajax(String username, MultipartFile[] files,
                           HttpServletRequest request) throws Exception {
        System.out.println("mingzi"+username);

        ResultData rd = new ResultData();
        //设置上传的文件所存放的路径
        String path = request.getServletContext().getRealPath("/files");
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址："+realPath);
        ObjectMapper mapper = new ObjectMapper();
        if (files != null && files.length > 0) {
            //循环获取上传的文件
            for (MultipartFile file : files) {
                //获取上传文件的名称
                String filename = System.currentTimeMillis() + file.getOriginalFilename();
                InputStream is = file.getInputStream(); //文件输入流
                OutputStream os = new FileOutputStream(new File(realPath,filename)); //文件输出流
                //读取写出
                int len=0;
                byte[] buffer = new byte[1024];
                while ((len=is.read(buffer))!=-1){
                    os.write(buffer,0,len);
                    os.flush();
                }
                os.close();
                is.close();

                rd.setData(filename);
            }
            rd.setMsg("上传成功");
            rd.setCode(0);
            return rd;
        }
        rd.setCode(10);
        rd.setMsg("上传失败！没有图片");
        return rd;
    }

    /**
     * 文件上传 使用ajax存到session
     */
    @RequestMapping("fileloadbyajaxtoshow")
    @ResponseBody
    public ResultData fileLoadByajaxtoshow(String username, MultipartFile[] files,
                                     HttpServletRequest request , ModelMap modelMap) throws Exception {
        System.out.println("mingzi"+username);

        ResultData rd = new ResultData();
        //设置上传的文件所存放的路径
        String path = request.getServletContext().getRealPath("/files");
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址："+realPath);
        ObjectMapper mapper = new ObjectMapper();
        String filepath ="";
        if (files != null && files.length > 0) {
            //循环获取上传的文件
            for (MultipartFile file : files) {
                //获取上传文件的名称
                String filename = System.currentTimeMillis() + file.getOriginalFilename();
                InputStream is = file.getInputStream(); //文件输入流
                OutputStream os = new FileOutputStream(new File(realPath,filename)); //文件输出流
                //读取写出
                int len=0;
                byte[] buffer = new byte[1024];
                while ((len=is.read(buffer))!=-1){
                    os.write(buffer,0,len);
                    os.flush();
                }
                os.close();
                is.close();

                rd.setData(filename);
                filepath = filename;
            }
            User user = new User();
            user.setUsername(username);
            //user.setFilepath(filepath);

            modelMap.addAttribute("userinfo1", user);

            rd.setCode(0);
            return rd;
        }
        rd.setCode(10);
        rd.setMsg("上传失败！没有图片");
        return rd;
    }



    /**
     * 文件下载 io方式下载
     */
    @RequestMapping("/download1")
    public String fileDownload1(HttpServletRequest request,HttpServletResponse response ,
                                               String filename) throws Exception {
        //要下载的图片地址
        String  path = request.getServletContext().getRealPath("/files");
        String  fileName = filename;

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path + File.separator +fileName);
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return "forward:fileload.jsp";
    }


    /**
     * 文件下载 ResponseEntity方式下载
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
                                               String filename) throws Exception {
        // 指定要下载的文件所在路径
        String path = request.getServletContext().getRealPath("/files/");
        // 创建该文件对象
        File file = new File(path + File.separator + filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        filename = this.getFileName(request, filename);
        // 通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);
    }

    /**
     * 根据浏览器的不同进行编码设置，返回编码后的文件名
     */
    public String getFileName(HttpServletRequest request,
                              String filename) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String agent = request.getHeader("User-Agent");
        if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = "=?UTF-8?B?" + new String
                    (base64Encoder.encode(filename.getBytes("UTF-8"))) + "?=";
        } else {
            // IE及其他浏览器
            filename = URLEncoder.encode(filename, "UTF-8");
        }
        return filename;
    }

}

